<template>
  <div class="register">
    <div class="container">
      <div class="row">
        <div class="col-md-8 m-auto">
          <h1 class="display-4 text-center">注册</h1>
          <p class="lead text-center">创建新的账户</p>
          <form @submit.prevent="submit" autocomplete="off" method="post">
            <TextFiled
              type="text"
              name="name"
              placeholder="用户名"
              v-model="newUser.name"
              :error="error.name"
            ></TextFiled>
            <TextFiled
              type="email"
              name="email"
              placeholder="邮箱地址"
              v-model="newUser.email"
              :error="error.email"
              info="我们使用了gravatar全球公认头像, 如果需要有头像显示, 请使用在gravatar注册的邮箱"
            ></TextFiled>
            <TextFiled
              type="password"
              name="password"
              placeholder="密码"
              v-model="newUser.password"
              :error="error.password"
            ></TextFiled>
            <TextFiled
              type="password"
              name="password2"
              placeholder="确认密码"
              v-model="newUser.password2"
              :error="error.password2"
            ></TextFiled>
            <input type="submit" class="btn btn-info btn-block mt-4">
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import TextFiled from "./common/TextFiled";

export default {
  data() {
    return {
      newUser: {
        name: "",
        email: "",
        password: "",
        password2: ""
      },
      error: {}
    };
  },
  components: {
    TextFiled
  },
  methods: {
    submit() {
      // console.log(this.$store.getters.isAuthenticated);

      // console.log(this.newUser.name);
      this.$axios
        .post("http://localhost:5000/api/users/register", this.newUser)
        .then(res => {
          // console.log(res.data);

          //清除错误
          this.error = {};

          //执行action异步操作
          this.$store.dispatch("setUser", res.data);

          // 路由跳转
          this.$router.push("/login");
        })
        .catch(err => {
          if (err.response.data) {
            this.error = err.response.data;
          }
        });
    }
  },
  beforeRouteEnter(to, from, next) {
    // ...
    next(vm => {
      vm.error = {};
    });
  }
};
</script>

<style scoped lang="stylus">
</style>
